package com.genghis.ptas.inbox.dao.impl;

import com.genghis.core.page.dao.PageDao;
import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.inbox.dao.InboxDao;
import com.genghis.ptas.inbox.entity.Inbox;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: gaoyang
 * To change this template use File | Settings | File Templates.
 */
@Repository("InboxDao")
public class InboxDaoImpl extends PageDao implements InboxDao {
    @Override
    public int addInbox(Inbox inbox) {
        String sql = "INSERT INTO inbox(`user_id`,`content`,`category`, `state`, send_date, addressee_id) VALUES(:userId, :content, :category, :state, :sendDate, :addresseeId)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        getNamedParameterJdbcTemplate().update(sql, new BeanPropertySqlParameterSource(inbox), keyHolder);
        return keyHolder.getKey().intValue();
    }

    @Override
    public void delInbox(String ids) {
        String sql = "DELETE FROM inbox WHERE id in(" + ids + ")";
        getJdbcTemplate().update(sql);
    }

    @Override
    public List<Inbox> listAllInbox(Inbox inbox) {
        StringBuilder sql = new StringBuilder("SELECT * FROM `inbox` WHERE `user_id`=" + inbox.getUserId());
        if (inbox.getState() != -1) {
            sql.append(" AND state =").append(inbox.getState()).append(" ");
        } else {
            sql.append(" AND state !=").append(DictConstant.INBOX_STATE_4).append(" ");
        }
        if (inbox.getCategory() != 0) {
            sql.append(" AND category =").append(inbox.getCategory()).append(" ");
        }
        return getJdbcTemplate().query(sql.toString(), new BeanPropertyRowMapper<Inbox>(Inbox.class));
    }

    @Override
    public Inbox findInboxById(int id) {
        String sql = "select * from inbox where id=" + id;
        return getJdbcTemplate().queryForObject(sql, new BeanPropertyRowMapper<Inbox>(Inbox.class));
    }

    @Override
    public void changeMassageState(String state, String ids) {
        String sql = "UPDATE inbox SET state =? WHERE id IN (" + ids + ")";
        getJdbcTemplate().update(sql, state);
    }

    @Override
    public void changeMassageCategory(String category, String ids) {
        String sql = "UPDATE inbox SET category =? WHERE id IN (" + ids + ")";
        getJdbcTemplate().update(sql, category);
    }

    @Override
    public void delMassage(String ids) {
        String sql = "DELETE FROM inbox WHERE id IN (" + ids + ")";
        getJdbcTemplate().update(sql);
    }
}